﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace BPMS.Core.DataAccess
{
    public class DbTransactionProvider : IDisposable
    {
        private bool isDisposed = false;
        private IsolationLevel isolationLevel = IsolationLevel.ReadCommitted;
        public DbTransaction Transaction { get; private set; }
        public IsolationLevel IsolationLevel
        {
            get { return isolationLevel; }
            set { isolationLevel = value; }
        }
        public DbTransactionProvider()
        {
            this.Transaction = null;
        }

        public DbTransaction CreateTransaction(DbConnection connection)
        {
            Transaction = connection.BeginTransaction(this.IsolationLevel);
            return Transaction;
        }

        public void CommitTransaction()
        {
            if (null != Transaction)
            {
                Transaction.Commit();
                Transaction.Dispose();
                Transaction = null;
            }
        }

        public void RollbackTransaction()
        {
            if (null != Transaction)
            {
                Transaction.Rollback();
                Transaction.Dispose();
                Transaction = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!isDisposed)
                {
                    if (null != Transaction)
                    {
                        Transaction.Dispose();
                    }
                    isDisposed = true;
                }
            }
        }
    }
}
